package com.meryl.dtk;

import com.intellij.ide.IdeView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.impl.file.PsiDirectoryFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CreateSqlAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();

        IdeView ideView = e.getRequiredData(LangDataKeys.IDE_VIEW);
        PsiDirectory directory = ideView.getOrChooseDirectory();
        VirtualFile dirPath = directory.getVirtualFile();
        String path = dirPath.getPath();

        String packageName = path.substring(path.indexOf("java") + 5).replace("/", ".");
        String xmlName = Messages.showInputDialog("Controller Name", "Create JDS Controller", Messages.getInformationIcon());
        if (xmlName == null) {
            return;
        }

        if (!packageName.contains("module")) {
            Messages.showErrorDialog(new String("项目中不包含Jds模块，请先创建Jds模块".getBytes(), StandardCharsets.UTF_8), "Error");
            return;
        }

        String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                "<mapper namespace=\"" + xmlName + "\">\n" +
                "\n" +
                "</mapper>";


        WriteCommandAction.runWriteCommandAction(project, () -> {
            try {
                PsiDirectoryFactory.getInstance(project)
                        .createDirectory(dirPath)
                        .createFile(xmlName + ".xml")
                        .getVirtualFile()
                        .setBinaryContent(text.getBytes(StandardCharsets.UTF_8));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}
